package com.windea.study.kotlin.jvm.spam

import com.windea.study.kotlin.jvm.spam.extensions.*
import org.apache.http.*
import org.apache.http.client.entity.*
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.message.*
import org.apache.http.util.*
import java.io.*

class Application

fun main() {
	//参考：https://blog.csdn.net/wanglha/article/details/51140846
	//FIXME javax.net.ssl.SSLHandshakeException
	//val keystoreFile = File("D:\\My Documents\\My Projects\\Study\\Kotlin-Study\\learn-kotlin-spam\\key.store")
	//val sslContext = SSLContextBuilder.create().loadTrustMaterial(keystoreFile, "password".toCharArray()).build()
	//val httpClient = HttpClientBuilder.create().setSSLContext(sslContext).build()
	
	//val httpClient = createSSLHttpClient()
	val httpClient = HttpClientBuilder.create().setProxy(HttpHost("127.0.0.1", 19180, "http")).build()
	
	//模拟登录
	//FIXED connect reset 需要设置代理
	//FIXME 400 猜测：reCaptcha导致表单输入仍然不合法
	val loginUrl = "https://accounts.pixiv.net/login"
	val nvps = listOf(
		"pixiv_id" to "oneboynimor@gmail.com",
		"password" to "******"
	).map { it.toNameValuePair() }
	val postRequest = RequestBuilder.post(loginUrl)
		.addBody(UrlEncodedFormEntity(nvps, "UTF-8"))
		.build()
	val postResponse = httpClient.execute(postRequest)
	println(postResponse.statusLine)
	
	val cookie = postResponse.getFirstHeader("Set-Cookie").value
	
	//FIXME 403
	//val httpClient = sslHttpClientBuild()
	
	//抓取图片
	val imgUrl = "75878503_p0.png"
	val fullUri = "https://i.pximg.net/img-original/img/2019/07/24/00/00/02/$imgUrl"
	val getRequest = RequestBuilder.get(fullUri).addHeader("Cookie", cookie).build()
	val getResponse = httpClient.execute(getRequest)
	println(getResponse.statusLine)
	val file = File("D:\\My Documents\\My Projects\\Study\\Kotlin-Study\\learn-kotlin-spam\\download\\$imgUrl")
	file.writeBytes(EntityUtils.toByteArray(getResponse.entity))
	EntityUtils.consume(getResponse.entity)
}

//fun createSSLHttpClient(): CloseableHttpClient {
//	val sslContext = SSLContextBuilder.create().loadTrustMaterial(null) { _, _ -> true }.build()
//	val sslConnectionSocketFactory = SSLConnectionSocketFactory(sslContext)
//	return HttpClientBuilder.create().setSSLSocketFactory(sslConnectionSocketFactory).setRetryHandler { exception, executionCount, context ->
//		when {
//			// 如果超过最大重试次数，那么就不要继续了
//			executionCount >= 3 -> false
//			// 如果服务器丢掉了连接，那么就重试
//			exception is NoHttpResponseException -> true
//			// 不要重试SSL握手异常
//			exception is SSLHandshakeException -> false
//			// 如果请求被认为是幂等的，那么就重试
//			context.getAttribute(HttpCoreContext.HTTP_REQUEST) !is HttpEntityEnclosingRequest -> true
//			else -> false
//		}
//	}.build()
//}

fun Pair<String, String>.toNameValuePair(): BasicNameValuePair {
	return BasicNameValuePair(this.first, this.second)
}
